package com.widget;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * Created by chentao on 2018/6/25.
 */

public class HorizontalProgressView extends LinearLayout {
    private ObjectAnimator mAnimator;
    private ProgressBar mProgressBar;
    private TextView mProgressTxt;
    private int mWidth1 = 0;
    private int mWidth2 = 0;
    private int mStart = 0;
    private int mEnd = 0;

    public HorizontalProgressView(Context context) {
        this(context, null);
    }

    public HorizontalProgressView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOrientation(VERTICAL);
        View view = LayoutInflater.from(context).inflate(R.layout.view_horizontal_progress, this);
        mProgressBar = (ProgressBar) view.findViewById(R.id.progressbar);
        mProgressTxt = (TextView) view.findViewById(R.id.txt_progress);
    }

    public void updateProgress(int progress) {
        if(progress > 100 || progress < 0) {
            return;
        }
        mProgressBar.setProgress(progress);
        mProgressTxt.setText(progress + "%");
        mEnd = mWidth1 + mWidth2*progress/100;
        mAnimator = ObjectAnimator.ofFloat(mProgressTxt, "x", mStart, mEnd);
        mAnimator.start();
        mStart = mEnd;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth1 = mProgressTxt.getMeasuredWidth();
        mWidth2 = mProgressBar.getMeasuredWidth();
    }
}
